package com.biwei.app.wrap.controller;

import com.biwei.app.wrap.remote.UserRemoteService;
import com.biwei.app.wrap.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("wrap/proxy")
public class ProxyController {

    private static final Logger log = LoggerFactory.getLogger(ProxyController.class);

    private UserRemoteService userRemoteService;

    public ProxyController(UserRemoteService userRemoteService) {
        this.userRemoteService = userRemoteService;
    }

    @GetMapping("**")
    public void proxy(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, String> map = new HashMap<>(request.getParameterMap().size() * 2);
        request.getParameterMap().forEach((k, v) -> {
            map.put(k, v[0]);
        });
        Object resp = userRemoteService.proxy(request.getRequestURI().substring(11), map);
        if (resp != null) {
            JsonUtil.writeResponse(resp, response);
        }
    }

    @PostMapping("**")
    public void proxyPost(@RequestBody(required = false) String body, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Object resp = userRemoteService.proxyPost(request.getRequestURI().substring(11), body);
        if (resp != null) {
            JsonUtil.writeResponse(resp, response);
        }
    }

    @PostMapping("user/getGeetest")
    public void getGeetest(@RequestBody(required = false) String body, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Object resp = userRemoteService.proxyPost(request.getRequestURI().substring(11), body);
        if (resp != null) {
            String json = resp.toString();
            json = json.replaceAll("\\\\\"", "\"").replaceAll("\"\\{", "{").replaceAll("\\}\"", "}");
            JsonUtil.writeResponse(json, response);
        }
    }
}
